﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetFrame;
using NetFrame.auto;
using Server.tool;
using MoneyProtocol;
using MoneyProtocol.dto;
using System.Data;

namespace Server.logic.login
{
    public class StockHandler : AbsOnceHandler, HandlerInterface
    {
        cache.IAccountCache ac = cache.CacheFactory.accountCache;
        model.stock_day_count sc = new model.stock_day_count();

        public void ClientClose(UserToken token, string error)
        {
            ExecutorPool.Instance.execute(
                     delegate ()
                     {
                     }
                     );
        }

        public void MessageReceive(UserToken token, SocketModel message)
        {
            switch (message.command)
            {
                case StockProtocol.GET_CREQ:
                    getStockList(token, message.GetMessage<string>());
                    break;
                case StockProtocol.ADD_CREQ:
                    addStock(token, message.GetMessage<StockInfoDTO>());
                    break;
                case StockProtocol.UPDATE_CREQ:
                    updateStock(token, message.GetMessage<StockInfoDTO>());
                    break;
                case StockProtocol.DELETE_CREQ:
                    deleteStock(token, message.GetMessage<int[]>());
                    break;
                default:
                    break;
            }
        }

        #region getStockList
        private void getStockList(UserToken token, string sendMsg)
        {
            ExecutorPool.Instance.execute(
                     delegate ()
                     {
                         string[] s = sendMsg.Split('+');

                         Console.WriteLine("ID为：" + ac.getId(token) + "的用户正在进行获取证券账号ID为： " + s[0] + " 的股票交易记录");

                         string strWhere = "`security_day_account_id`=" + s[0];
                         DateTime datetime = DateTime.Parse(s[1]);
                         DateTime datetime2;
                         List<StockInfoDTO> stocks = new List<StockInfoDTO>();

                         DataSet ds = sc.GetList(strWhere);
                         foreach(DataRow dr in ds.Tables[0].Rows)
                         {
                             datetime2 = DateTime.Parse(dr["trade_date"].ToString());
                             if(datetime2.Year == datetime.Year && datetime2.Month == datetime.Month)
                             {
                                 StockInfoDTO stock = new StockInfoDTO(
                                     int.Parse(dr["id"].ToString()),
                                     int.Parse(s[0]),
                                     datetime2.ToString("yyyy/MM/dd"),
                                     dr["trade_type"].ToString(),
                                     dr["stock_name"].ToString(),
                                     int.Parse(dr["stock_code"].ToString()),
                                     float.Parse(dr["price"].ToString()),
                                     int.Parse(dr["num"].ToString()),
                                     float.Parse(dr["fee"].ToString()),
                                     dr["remark"].ToString());
                                 stocks.Add(stock);
                             }
                         }
                         write(token, StockProtocol.GET_SRES, stocks);
                     }
                     );
        }
        #endregion

        #region addStock
        private void addStock(UserToken token, StockInfoDTO msg)
        {
            ExecutorPool.Instance.execute(
                     delegate ()
                     {
                         Console.WriteLine("ID为：" + ac.getId(token) + "的用户正在进行为证券账号ID: " + msg.security_account_id + " 增加股票交易记录");

                         setStockDayCountObject(msg);
                         int result;
                         if (sc.Add()) result = sc.GetMaxId();
                         else result = -1;
                         write(token, StockProtocol.ADD_SRES, result);
                     }
                     );
        }
        #endregion

        #region updateStock
        private void updateStock(UserToken token, StockInfoDTO msg)
        {
            ExecutorPool.Instance.execute(
                     delegate ()
                     {
                         Console.WriteLine("ID为：" + ac.getId(token) + "的用户正在进行修改证券账号 " + msg.security_account_id + " 的股票交易记录");

                         setStockDayCountObject(msg);
                         bool result = sc.Update();
                         write(token, StockProtocol.UPDATE_SRES, result);
                     }
                     );
        }
        #endregion

        #region deleteStock
        private void deleteStock(UserToken token, int[] ids)
        {
            ExecutorPool.Instance.execute(
                     delegate ()
                     {
                         Console.WriteLine("ID为：" + ac.getId(token) + "的用户正在进行删除股票交易记录，共需删除 " + " 条记录");

                         int result = 0;
                         foreach(int id in ids)
                         {
                             if (sc.Delete(id))
                                 result++;
                         }

                         Console.WriteLine("已完成" + result + "记录的删除");

                         write(token, StockProtocol.DELETE_SRES, result);
                     }
                     );
        }
        #endregion

        private void setStockDayCountObject(StockInfoDTO msg)
        {
            sc.id = msg.id;
            sc.security_day_account_id = msg.security_account_id;
            sc.trade_date = DateTime.Parse(msg.date);
            sc.trade_type = msg.trade_type;
            sc.stock_name = msg.stock_name;
            sc.stock_code = msg.stock_code;
            sc.price = msg.price;
            sc.num = msg.stock_num;
            sc.fee = msg.fee;
            sc.remark = msg.remark;
        }

        public override byte GetType()
        {
            return Protocol.TYPE_SECURITYRECORD;
        }
    }
}
